#include "income_chart_widget.h"
#include <QPainter>
#include <QPainterPath>
#include <QTimer>
#include <QDateTime>
#include <QFontMetrics>
#include <QFont>
#include <QLinearGradient>
#include <QDebug>
#include <QResizeEvent>

IncomeChartWidget::IncomeChartWidget(QWidget *parent)
    : QWidget(parent)
    , m_title("实时收入趋势图")
    , m_timeRange(24)
    , m_maxDataPoints(50)
    , m_animationEnabled(true)
    , m_refreshInterval(1000)
    , m_marginLeft(60)
    , m_marginRight(40)
    , m_marginTop(40)
    , m_marginBottom(60)
    , m_minValue(0)
    , m_maxValue(100)
    , m_valueRange(100)
    , m_animationProgress(0)
    , m_lineWidth(2)
    , m_pointRadius(4)
    , m_showPoints(true)
    , m_showGrid(true)
    , m_showLegend(true)
{
    // 初始化动画定时器
    m_animationTimer = new QTimer(this);
    connect(m_animationTimer, &QTimer::timeout, this, &IncomeChartWidget::onTimerTimeout);
    
    // 设置默认样式
    updateColors();
    
    // 设置最小大小
    setMinimumSize(400, 200);
    
    // 启用鼠标跟踪
    setMouseTracking(true);
    
    qDebug() << "IncomeChartWidget 初始化完成";
}

void IncomeChartWidget::updateChart(const QStringList &labels, const QList<double> &values)
{
    if (labels.size() != values.size()) {
        qDebug() << "标签和数值数量不匹配";
        return;
    }
    
    m_labels = labels;
    m_values = values;
    
    // 限制数据点数量
    if (m_labels.size() > m_maxDataPoints) {
        int removeCount = m_labels.size() - m_maxDataPoints;
        m_labels = m_labels.mid(removeCount);
        m_values = m_values.mid(removeCount);
    }
    
    // 计算数据范围
    calculateBounds();
    
    // 启动动画
    if (m_animationEnabled) {
        m_animatedValues.clear();
        for (int i = 0; i < m_values.size(); ++i) {
            m_animatedValues.append(0);
        }
        m_animationProgress = 0;
        m_animationTimer->start(30); // 30ms刷新率，约33fps
    } else {
        m_animatedValues = m_values;
        update();
    }
    
    qDebug() << "图表数据更新，数据点数:" << m_values.size();
}

void IncomeChartWidget::addDataPoint(const QString &label, double value)
{
    m_labels.append(label);
    m_values.append(value);
    
    // 限制数据点数量
    if (m_labels.size() > m_maxDataPoints) {
        m_labels.removeFirst();
        m_values.removeFirst();
    }
    
    // 计算数据范围
    calculateBounds();
    
    // 更新动画
    if (m_animationEnabled) {
        m_animatedValues.append(0);
        if (m_animatedValues.size() > m_maxDataPoints) {
            m_animatedValues.removeFirst();
        }
        m_animationProgress = 0;
        m_animationTimer->start(30);
    } else {
        m_animatedValues = m_values;
        update();
    }
}

void IncomeChartWidget::clearData()
{
    m_labels.clear();
    m_values.clear();
    m_animatedValues.clear();
    m_animationProgress = 0;
    m_animationTimer->stop();
    update();
}

void IncomeChartWidget::setTitle(const QString &title)
{
    m_title = title;
    update();
}

void IncomeChartWidget::setTimeRange(int hours)
{
    m_timeRange = hours;
    update();
}

void IncomeChartWidget::setMaxDataPoints(int maxPoints)
{
    m_maxDataPoints = maxPoints;
    
    // 调整现有数据
    while (m_labels.size() > m_maxDataPoints) {
        m_labels.removeFirst();
        m_values.removeFirst();
    }
    while (m_animatedValues.size() > m_maxDataPoints) {
        m_animatedValues.removeFirst();
    }
}

void IncomeChartWidget::setAnimationEnabled(bool enabled)
{
    m_animationEnabled = enabled;
    if (!enabled) {
        m_animationTimer->stop();
        m_animatedValues = m_values;
        update();
    }
}

void IncomeChartWidget::setRefreshInterval(int intervalMs)
{
    m_refreshInterval = intervalMs;
}

void IncomeChartWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    
    // 绘制背景
    drawBackground(painter);
    
    // 计算图表区域
    m_chartRect = QRect(m_marginLeft, m_marginTop, 
                       width() - m_marginLeft - m_marginRight,
                       height() - m_marginTop - m_marginBottom);
    
    if (!m_chartRect.isValid()) {
        return;
    }
    
    // 绘制网格
    if (m_showGrid) {
        drawGrid(painter);
    }
    
    // 绘制坐标轴
    drawAxes(painter);
    
    // 绘制数据
    if (!m_animatedValues.isEmpty()) {
        drawData(painter);
    }
    
    // 绘制图例
    if (m_showLegend && !m_title.isEmpty()) {
        drawTitle(painter);
    }
}

void IncomeChartWidget::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event)
    update();
}

void IncomeChartWidget::onTimerTimeout()
{
    if (m_animationProgress < 1.0) {
        m_animationProgress += 0.05; // 动画速度
        if (m_animationProgress > 1.0) {
            m_animationProgress = 1.0;
        }
        
        // 更新动画值
        for (int i = 0; i < m_values.size(); ++i) {
            if (i < m_animatedValues.size()) {
                m_animatedValues[i] = m_values[i] * m_animationProgress;
            }
        }
        
        update();
    } else {
        m_animationTimer->stop();
        m_animatedValues = m_values;
    }
}

void IncomeChartWidget::drawBackground(QPainter &painter)
{
    painter.fillRect(rect(), m_backgroundColor);
}

void IncomeChartWidget::drawGrid(QPainter &painter)
{
    painter.setPen(QPen(m_gridColor, 1, Qt::DashLine));
    
    // 绘制水平网格线
    int horizontalLines = 5;
    for (int i = 0; i <= horizontalLines; ++i) {
        int y = m_chartRect.top() + (m_chartRect.height() * i / horizontalLines);
        painter.drawLine(m_chartRect.left(), y, m_chartRect.right(), y);
    }
    
    // 绘制垂直网格线
    int verticalLines = m_labels.size() - 1;
    if (verticalLines > 0) {
        for (int i = 0; i <= verticalLines; ++i) {
            int x = m_chartRect.left() + (m_chartRect.width() * i / verticalLines);
            painter.drawLine(x, m_chartRect.top(), x, m_chartRect.bottom());
        }
    }
}

void IncomeChartWidget::drawAxes(QPainter &painter)
{
    painter.setPen(QPen(m_axisColor, 2));
    
    // 绘制X轴
    painter.drawLine(m_chartRect.left(), m_chartRect.bottom(), 
                    m_chartRect.right(), m_chartRect.bottom());
    
    // 绘制Y轴
    painter.drawLine(m_chartRect.left(), m_chartRect.top(), 
                    m_chartRect.left(), m_chartRect.bottom());
    
    // 绘制Y轴标签
    painter.setPen(m_textColor);
    QFont font = painter.font();
    font.setPointSize(9);
    painter.setFont(font);
    
    int horizontalLines = 5;
    for (int i = 0; i <= horizontalLines; ++i) {
        double value = m_minValue + (m_valueRange * (horizontalLines - i) / horizontalLines);
        QString label = QString("¥%1").arg(value, 0, 'f', 0);
        
        int y = m_chartRect.top() + (m_chartRect.height() * i / horizontalLines);
        QRect textRect(m_marginLeft - 50, y - 10, 45, 20);
        painter.drawText(textRect, Qt::AlignRight | Qt::AlignVCenter, label);
    }
    
    // 绘制X轴标签（时间）
    if (!m_labels.isEmpty()) {
        int labelCount = qMin(m_labels.size(), 8); // 最多显示8个时间标签
        int step = m_labels.size() / labelCount;
        
        for (int i = 0; i < labelCount; ++i) {
            int index = i * step;
            if (index < m_labels.size()) {
                QString label = m_labels[index];
                int x = m_chartRect.left() + (m_chartRect.width() * index / (m_labels.size() - 1));
                QRect textRect(x - 30, m_chartRect.bottom() + 5, 60, 20);
                painter.drawText(textRect, Qt::AlignCenter, label);
            }
        }
    }
    
    // 绘制轴标题
    font.setBold(true);
    painter.setFont(font);
    
    // Y轴标题
    QRect yAxisTitle(m_marginLeft - 55, m_chartRect.center().y() - 40, 50, 80);
    painter.drawText(yAxisTitle, Qt::AlignCenter, "收入金额");
    
    // X轴标题
    QRect xAxisTitle(m_chartRect.center().x() - 40, height() - 25, 80, 20);
    painter.drawText(xAxisTitle, Qt::AlignCenter, "时间");
}

void IncomeChartWidget::drawData(QPainter &painter)
{
    if (m_animatedValues.size() < 2) {
        return;
    }
    
    // 创建渐变填充
    QLinearGradient gradient(m_chartRect.left(), m_chartRect.top(),
                            m_chartRect.left(), m_chartRect.bottom());
    gradient.setColorAt(0, QColor(26, 115, 232, 100));
    gradient.setColorAt(1, QColor(26, 115, 232, 20));
    
    // 绘制填充区域
    QPainterPath fillPath;
    fillPath.moveTo(dataPointToScreen(m_labels[0], 0));
    
    for (int i = 0; i < m_animatedValues.size(); ++i) {
        QPointF point = dataPointToScreen(m_labels[i], m_animatedValues[i]);
        fillPath.lineTo(point);
    }
    
    fillPath.lineTo(dataPointToScreen(m_labels[m_animatedValues.size() - 1], 0));
    fillPath.closeSubpath();
    
    painter.fillPath(fillPath, gradient);
    
    // 绘制数据线
    painter.setPen(QPen(m_dataColor, m_lineWidth));
    QPainterPath linePath;
    
    for (int i = 0; i < m_animatedValues.size(); ++i) {
        QPointF point = dataPointToScreen(m_labels[i], m_animatedValues[i]);
        if (i == 0) {
            linePath.moveTo(point);
        } else {
            linePath.lineTo(point);
        }
    }
    
    painter.drawPath(linePath);
    
    // 绘制数据点
    if (m_showPoints) {
        painter.setPen(QPen(m_dataColor, 2));
        painter.setBrush(m_dataColor);
        
        for (int i = 0; i < m_animatedValues.size(); ++i) {
            QPointF point = dataPointToScreen(m_labels[i], m_animatedValues[i]);
            painter.drawEllipse(point, m_pointRadius, m_pointRadius);
        }
    }
}

void IncomeChartWidget::drawLegend(QPainter &painter)
{
    // 绘制图例（如果需要）
}

void IncomeChartWidget::drawTitle(QPainter &painter)
{
    painter.setPen(m_titleColor);
    QFont font = painter.font();
    font.setPointSize(12);
    font.setBold(true);
    painter.setFont(font);
    
    QRect titleRect(m_chartRect.left(), 10, m_chartRect.width(), 30);
    painter.drawText(titleRect, Qt::AlignCenter, m_title);
}

double IncomeChartWidget::normalizeValue(double value)
{
    if (m_valueRange == 0) {
        return 0;
    }
    return (value - m_minValue) / m_valueRange;
}

QPointF IncomeChartWidget::dataPointToScreen(const QString &label, double value)
{
    double xRatio = 0;
    if (m_labels.size() > 1) {
        int index = m_labels.indexOf(label);
        if (index >= 0) {
            xRatio = (double)index / (m_labels.size() - 1);
        }
    }
    
    double yRatio = 1.0 - normalizeValue(value);
    
    int x = m_chartRect.left() + (m_chartRect.width() * xRatio);
    int y = m_chartRect.top() + (m_chartRect.height() * yRatio);
    
    return QPointF(x, y);
}

void IncomeChartWidget::calculateBounds()
{
    if (m_values.isEmpty()) {
        m_minValue = 0;
        m_maxValue = 100;
        m_valueRange = 100;
        return;
    }
    
    m_minValue = *std::min_element(m_values.begin(), m_values.end());
    m_maxValue = *std::max_element(m_values.begin(), m_values.end());
    
    // 添加一些边距
    double margin = (m_maxValue - m_minValue) * 0.1;
    m_minValue = qMax(0.0, m_minValue - margin);
    m_maxValue = m_maxValue + margin;
    m_valueRange = m_maxValue - m_minValue;
    
    if (m_valueRange == 0) {
        m_valueRange = 100;
    }
}

void IncomeChartWidget::updateColors()
{
    m_backgroundColor = QColor(248, 249, 250);
    m_gridColor = QColor(218, 220, 224);
    m_axisColor = QColor(60, 64, 67);
    m_dataColor = QColor(26, 115, 232);
    m_textColor = QColor(95, 99, 104);
    m_titleColor = QColor(26, 115, 232);
}